<template>
  <div style="height: 100%; width: 100%">
    <van-nav-bar fixed placeholder v-if="!hideNavBar" :title="title">
      <template #left>
        <van-icon @click="to_back" v-show="!isMenu && !$route.meta.hide_back" color="white" size="18" name="revoke" />
      </template>
      <template #right>
        <avatar v-if="username" :name="username" @click="to_myinfo"></avatar>
      </template>
    </van-nav-bar>
    <router-view v-slot="{ Component }">
      <transition>
        <keep-alive :include="['stockin']">
          <component ref="child" :is="Component" />
        </keep-alive>
      </transition>
    </router-view>
    <van-overlay :show="loading">
      <div class="loading_wrapper"><van-loading type="spinner" size="24" /></div
    ></van-overlay>
  </div>
</template>
<script setup lang="ts">
import { RouterView, useRouter } from 'vue-router';
import { whoami } from '@/api/user';
import { ref, watch } from 'vue';
import { useUserStore } from './stores/userInfo';
const router = useRouter();
const hideNavBar = ref(false);
const isMenu = ref(false);
const title = ref('');
const loading = ref(false);
const username = ref('');
const child = ref(null);

watch(
  () => router.currentRoute.value,
  (to, from) => {
    const r = to;
    const login_require = !(r.name === 'login' || r.name === 'setting');
    hideNavBar.value = !login_require;
    isMenu.value = r.name === 'menu' || r.name === 'home';
    title.value = r.meta.title as string;
    const user = useUserStore();
    if (login_require) {
      if (!user.token) router.push('/login');
      else {
        loading.value = true;
        whoami()
          .then((r) => {
            console.log('aaa');
            username.value = user.user?.UserName!;
            loading.value = false;
          })
          .catch((e) => {
            loading.value = false;
          });
      }
    }
  },
  { immediate: true, deep: true }
);

const to_back = () => {
  const _child = child.value as any;
  if (_child && _child.beforeBack) _child.beforeBack();
  router.back();
};
const to_myinfo = () => {
  router.push('/info');
};
</script>
